package com.zhuangwei.controller;

import com.alibaba.fastjson.JSON;
import com.zhuangwei.config.OtherProperBean;
import com.zhuangwei.config.ProperBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 文希
 * @create 2019-05-24 18:01
 **/
@RestController
public class DemoController {
    // 方式一：通过Environment，读取配置文件中的信息
    @Autowired
    private Environment environment;

    // 方式二：配置必须存在，且获取的配置名为app.demo.val的配置信息
    @Value("${app.demo.val}")
    private String autoInject;
    // 配置app.demo.not不存在时，不抛异常，给一个默认值data
    @Value("${app.demo.not:dada}")
    private String notExists;
    @Value("${user.name}")
    private String name;

    @Autowired
    private ProperBean properBean;
    @Autowired
    private OtherProperBean otherProperBean;

    @GetMapping("/show1")
    public String show1(){
        Map<String, String> map = new HashMap<>(4);
        map.put("env",environment.getProperty("server.port"));
        return JSON.toJSONString(map);
    }

    @GetMapping("/show2")
    public String show2(){
        Map<String, String> map = new HashMap<>(4);
        map.put("autoInject",autoInject);
        map.put("not",notExists);
        return JSON.toJSONString(map);
    }

    @GetMapping(path = "show3")
    public String show3() {
        Map<String, String> result = new HashMap<>(6);
        result.put("properBean", properBean.toString());
        result.put("otherBean", otherProperBean.toString());
        result.put("autoInject", autoInject);
        result.put("env", environment.getProperty("server.port"));
        result.put("not", notExists);
        result.put("name", name);
        return JSON.toJSONString(result);
    }
}
